package com.shj.em.util;

import com.shj.em.aa.entity.User;
import com.shj.em.biz.Constants;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;

/**
 * @author Shen Huang Jian
 * @since 2018-06-21
 */

public class ShiroUtils {

    public static Subject getSubjct() {
        return SecurityUtils.getSubject();
    }

    public static User getUser() {
        return (User) getSubjct().getPrincipal();
    }

    public static String getUserId() {
        return getUser().getUserId();
    }

    public static boolean hasRole(String role){
        return getSubjct().hasRole(role);
    }

    public static boolean isSell(){
        return hasRole(Constants.ROLE_SELL_CD) || isSuperAdmin() || isManager();
    }

    public static boolean isManager(){
        return hasRole(Constants.ROLE_MANAGER) || isSuperAdmin();
    }

    public static boolean isSuperAdmin(){
        return hasRole(Constants.ROLE_SUPER);
    }

    public static boolean isAdmin(){
        return hasRole(Constants.ROLE_ADMIN);
    }

    public static boolean isFinancial(){
        return hasRole(Constants.ROLE_FINACIAL) || isSuperAdmin() || isManager();
    }

    public static boolean isPurchase(){
        return hasRole(Constants.ROLE_PURCHASE) || isSuperAdmin() || isManager();
    }

    public static boolean isSupply(){
        return hasRole(Constants.ROLE_SUPPLY) || isSuperAdmin() || isManager();
    }

    public static boolean isProd(){
        return hasRole(Constants.ROLE_PRODUCER) || isSuperAdmin() || isManager();
    }

    public static boolean hasPermission(String permission){
        try {
            SecurityUtils.getSubject().checkPermission(permission);
            return true;
        }catch (AuthorizationException ae){
            return false;
        }
    }

    public static void logout() {
        getSubjct().logout();
    }
}
